let COS = require('./cos-wx-sdk-v5');
// let configV5 = require('./config-v5');
let $api = require('../network/api/cosV5');
let cosArr = [],
    locations = [],
    TaskIdArr = [],
    getAuthorizationArr = [];
    
// let locations =  [{
//     "filename": "test.png",          //文件名
//     "bucket": "ykt-1257239499",     //存储桶名称
//     "region": "ap-guangzhou",       //
//     "key": "upload/2020-09-14/13bb3670d52a51a3428d7ad87b8b93d1.png"
// }]

// 签名回调
// var getAuthorization = function(options, callback) {

// 格式一、（推荐）后端通过获取临时密钥给到前端，前端计算签名
// 服务端 JS 和 PHP 例子：https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
// 服务端其他语言参考 COS STS SDK ：https://github.com/tencentyun/qcloud-cos-sts-sdk
// wx.request({
//     method: 'GET',
//     url: configV5.stsUrl, // 服务端签名，参考 server 目录下的两个签名例子
//     dataType: 'json',
//     success: function(result) {
//         var data = result.data;
//         var credentials = data && data.credentials;
//         if (!data || !credentials) return console.error('credentials invalid');
//         callback({
//             TmpSecretId: credentials.tmpSecretId,
//             TmpSecretKey: credentials.tmpSecretKey,
//             XCosSecurityToken: credentials.sessionToken,
//             StartTime: data.startTime, // 时间戳，单位秒，如：1580000000，建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
//             ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
//         });
//     }
// });

// // 格式二、（推荐）【细粒度控制权限】后端通过获取临时密钥给到前端，前端只有相同请求才重复使用临时密钥，后端可以通过 Scope 细粒度控制权限
// // 服务端例子：https://github.com/tencentyun/qcloud-cos-sts-sdk/edit/master/scope.md
// wx.request({
//     method: 'POST',
//     url: 'http://127.0.0.1:3000/sts-scope',
//     data: options.Scope,
//     dataType: 'json',
//     success: function(result) {
//         var data = result.data;
//         var credentials = data && data.credentials;
//         if (!data || !credentials) return console.error('credentials invalid');
//         callback({
//             TmpSecretId: credentials.tmpSecretId,
//             TmpSecretKey: credentials.tmpSecretKey,
//             XCosSecurityToken: credentials.sessionToken,
//             StartTime: data.startTime, // 时间戳，单位秒，如：1580000000，建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
//             ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
//             ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
//         });
//     }
// });

// // 格式三、（不推荐，分片上传权限不好控制）前端每次请求前都需要通过 getAuthorization 获取签名，后端使用固定密钥或临时密钥计算签名返回给前端
// // 服务端获取签名，请参考对应语言的 COS SDK：https://cloud.tencent.com/document/product/436/6474
// // 注意：这种有安全风险，后端需要通过 method、pathname 严格控制好权限，比如不允许 put / 等
// wx.request({
//     method: 'POST',
//     url: 'https://example.com/sts-auth.php, // 服务端签名，参考 server 目录下的两个签名例子
//     data: {
//         method: options.Method,
//         pathname: options.Pathname,
//         query: options.Query,
//         headers: options.Headers,
//     },
//     dataType: 'json',
//     success: function(result) {
//         var data = result.data;
//         if (!data || !data.authorization) return console.error('authorization invalid');
//         callback({
//             Authorization: data.authorization,
//             // XCosSecurityToken: data.sessionToken, // 如果使用临时密钥，需要传 sessionToken
//         });
//     }
// });

// // 格式四、（不推荐，适用于前端调试，避免泄露密钥）前端使用固定密钥计算签名
// var authorization = COS.getAuthorization({
//     SecretId: 'AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
//     SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
//     Method: options.Method,
//     Pathname: options.Pathname,
//     Query: options.Query,
//     Headers: options.Headers,
//     Expires: 60,
// });
// callback({
//     Authorization: authorization,
//     // XCosSecurityToken: credentials.sessionToken, // 如果使用临时密钥，需要传 XCosSecurityToken
// });
// };

// // 创建一个 COS SDK 实例
// var cos = new COS({
//     // path style 指正式请求时，Bucket 是在 path 里，这样用途相同园区多个 bucket 只需要配置一个园区域名
//     // ForcePathStyle: true,
//     getAuthorization: getAuthorization,
// });

// 回调统一处理函数
var requestCallback = function(err, data) {
	console.log(err || data);
	if (err && err.error) {
		wx.showModal({
			title: '返回错误',
			content: '请求失败：' + (err.error.Message || err.error) + '；状态码：' + err.statusCode,
			showCancel: false
		});
	} else if (err) {
		wx.showModal({
			title: '请求出错',
			content: '请求出错：' + err + '；状态码：' + err.statusCode,
			showCancel: false
		});
	} else {
		// wx.showToast({
		// 	title: '请求成功',
		// 	icon: 'none',
		// 	duration: 3000
		// });
	}
};

// 展示的所有接口
var cosFun = {

    initData:function(){
        cosArr = []
        locations = []
        TaskIdArr = []
        getAuthorizationArr = [];
    },
    
    // 创建一个 COS SDK 实例的临时密钥必须参数
	getAuthorization: function(arr) {   
		return new Promise((resolve, reject) => {
			let params = {
				filenames: arr
			};
			$api
				.getSnapKey(params)
				.then((result) => {
                    var credentials = result.data;
					locations.push(credentials.locations[0]);
					let getAuthorization = function(options, callback) {
						if (!credentials) return console.error('credentials invalid');
						callback({
							TmpSecretId: credentials.tmpSecretId,
							TmpSecretKey: credentials.tmpSecretKey,
							XCosSecurityToken: credentials.sessionToken,
							StartTime: credentials.startTime, // 时间戳，单位秒，如：1580000000，建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
							ExpiredTime: credentials.expiredTime // 时间戳，单位秒，如：1580000900
						});
					};
                    getAuthorizationArr.push(getAuthorization);
                    let res = {
                        index:getAuthorizationArr.length - 1,
                        location:credentials.locations[0]
                    }
					resolve(res);
				})
				.catch((err) => {});
		});
    },
    
    // 创建一个 COS SDK 实例
	newCos: function(index) {
		return new Promise((resolve, reject) => {
			let cos = new COS({
				// path style 指正式请求时，Bucket 是在 path 里，这样用途相同园区多个 bucket 只需要配置一个园区域名
				// ForcePathStyle: true,
                getAuthorization: getAuthorizationArr[index],
                ProgressInterval:300,
			});
			cosArr.push(cos);
			resolve(true);
		});
	},

	getObjectUrl: function() {
		var url = cos.getObjectUrl(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				Region: configV5.Region,
				Key: '1mb.zip',
				Expires: 60,
				Sign: true
			},
			function(err, data) {
				console.log(err || data);
			}
		);
		console.log(url);
	},

	// 查询存储桶列表
	getService: function() {
		cos.getService(requestCallback);
	},

	// 简单 Bucket 操作
	putBucket: function() {
		cos.putBucket(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	getBucket: function() {
		cos.getBucket(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	headBucket: function() {
		cos.headBucket(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	deleteBucket: function() {
		cos.deleteBucket(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	getBucketACL: function() {
		cos.getBucketAcl(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	putBucketACL: function() {
		cos.putBucketAcl(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				ACL: 'public-read'
			},
			requestCallback
		);
	},

	getBucketCors: function() {
		cos.getBucketCors(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	putBucketCors: function() {
		cos.putBucketCors(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				CORSRules: [
					{
						AllowedOrigin: [ '*' ],
						AllowedMethod: [ 'GET', 'POST', 'PUT', 'DELETE', 'HEAD' ],
						AllowedHeader: [ '*' ],
						ExposeHeader: [ 'ETag', 'Content-Length' ],
						MaxAgeSeconds: '5'
					}
				]
			},
			requestCallback
		);
	},

	deleteBucketCors: function() {
		cos.deleteBucketCors(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},

	putBucketPolicy: function() {
		var AppId = configV5.Bucket.substr(configV5.Bucket.lastIndexOf('-') + 1);
		cos.putBucketPolicy(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Policy: {
					version: '2.0',
					principal: {
						qcs: [ 'qcs::cam::uin/10001:uin/10001' ]
					}, // 这里的 10001 是 QQ 号
					statement: [
						{
							effect: 'allow',
							action: [
								'name/cos:GetBucket',
								'name/cos:PutObject',
								'name/cos:PostObject',
								'name/cos:PutObjectCopy',
								'name/cos:InitiateMultipartUpload',
								'name/cos:UploadPart',
								'name/cos:UploadPartCopy',
								'name/cos:CompleteMultipartUpload',
								'name/cos:AbortMultipartUpload',
								'name/cos:AppendObject'
							],
							// "resource": ["qcs::cos:ap-guangzhou:uid/1250000000:test-1250000000/*"] // 1250000000 是 appid
							resource: [ 'qcs::cos:' + configV5.Region + ':uid/' + AppId + ':' + configV5.Bucket + '/*' ] // 1250000000 是 appid
						}
					]
				}
			},
			requestCallback
		);
	},
	getBucketPolicy: function() {
		cos.getBucketPolicy(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},
	deleteBucketPolicy: function() {
		cos.deleteBucketPolicy(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},
	getBucketLocation: function() {
		cos.getBucketLocation(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},
	getBucketTagging: function() {
		cos.getBucketTagging(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},
	putBucketTagging: function() {
		cos.putBucketTagging(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Tagging: {
					Tags: [
						{
							Key: 'k1',
							Value: 'v1'
						},
						{
							Key: 'k2',
							Value: 'v2'
						}
					]
				}
			},
			requestCallback
		);
	},
	deleteBucketTagging: function() {
		cos.deleteBucketTagging(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region
			},
			requestCallback
		);
	},
	// Object
	putObject: function() {
		cos.putObject(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt',
				Body: 'hello world' // 在小程序里，putObject 接口只允许传字符串的内容，不支持 TaskReady 和 onProgress，上传请使用 cos.postObject 接口
			},
			requestCallback
		);
	},
	getObject: function() {
		cos.getObject(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt'
			},
			requestCallback
		);
	},
	headObject: function() {
		cos.headObject(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt'
			},
			requestCallback
		);
	},
	deleteObject: function() {
		cos.deleteObject(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt'
			},
			requestCallback
		);
	},
	getObjectACL: function() {
		cos.getObjectAcl(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt'
			},
			requestCallback
		);
	},

	putObjectACL: function() {
		cos.putObjectAcl(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				Region: configV5.Region,
				Key: '1.txt',
				// GrantFullControl: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
				// GrantWrite: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
				// GrantRead: 'id="qcs::cam::uin/1001:uin/1001",id="qcs::cam::uin/1002:uin/1002"',
				// ACL: 'public-read-write',
				// ACL: 'public-read',
				// ACL: 'private',
				ACL: 'default' // 继承上一级目录权限
				// AccessControlPolicy: {
				//     "Owner": { // AccessControlPolicy 里必须有 owner
				//         "ID": 'qcs::cam::uin/459000000:uin/459000000' // 459000000 是 Bucket 所属用户的 QQ 号
				//     },
				//     "Grants": [{
				//         "Grantee": {
				//             "ID": "qcs::cam::uin/10002:uin/10002", // 10002 是 QQ 号
				//         },
				//         "Permission": "READ"
				//     }]
				// }
			},
			requestCallback
		);
	},

	deleteMultipleObject: function() {
		cos.deleteMultipleObject(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				Region: configV5.Region,
				Objects: [
					{
						Key: '1.txt'
					},
					{
						Key: '1.copy.txt'
					}
				]
			},
			requestCallback
		);
	},

	putObjectCopy: function() {
		cos.putObjectCopy(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				Region: configV5.Region,
				Key: '1.copy.txt',
				CopySource: configV5.Bucket + '.cos.' + configV5.Region + '.myqcloud.com/1.txt'
			},
			requestCallback
		);
	},

	// 上传文件
	postObject: function(params,callback,success) {
        // console.log(cosArr[params.index],'cosArr[params.index]')
		cosArr[params.index].postObject(
			{
				Bucket: locations[params.index].bucket, // Bucket 格式：test-1250000000
				Region: locations[params.index].region,
                Key: locations[params.index].key,
                ContentDisposition: `inline;filename=${locations[params.index].filename}`,
				FilePath: params.path,
                FileSize: params.size,
				TaskReady: function(taskId) {
					// console.log(taskId);
                    TaskIdArr.push(taskId)
				},
				onProgress: function(info) {
                    callback(info, {
                        filename:locations[params.index].filename,
                        Bucket: locations[params.index].bucket, // Bucket 格式：test-1250000000
                        Region: locations[params.index].region,
                        Key: locations[params.index].key,
                    })
					// console.log(info, 'cos.postObject');
					// console.log(JSON.stringify(info));
				}
			},
			function(err, data) {
                console.log(err || data);
                if (err && err.error) {
                    // wx.showModal({
                    //     title: '返回错误',
                    //     content: '请求失败：' + (err.error.Message || err.error) + '；状态码：' + err.statusCode,
                    //     showCancel: false
                    // });
                    wx.showModal({
                        title: '温馨提示',
                        content: '网络出错，请重试',
                        showCancel: false
                    });
                    success({statusCode:400},{msg:"返回出错！"})
                } else if (err) {
                    // wx.showModal({
                    //     title: '请求出错',
                    //     content: '请求出错：' + err + '；状态码：' + err.statusCode,
                    //     showCancel: false
                    // });
                    wx.showModal({
                        title: '温馨提示',
                        content: '网络出错，请重试',
                        showCancel: false
                    });
                    success({statusCode:400},{msg:"请求出错！"})
                } else {
                    success(data,{
                        filename:locations[params.index].filename,
                        Bucket: locations[params.index].bucket, // Bucket 格式：test-1250000000
                        Region: locations[params.index].region,
                        Key: locations[params.index].key,
                    })
                }
            }
		);
	},

	// 上传文件
	postObjectByBase64Url: function() {
		var base64Url =
			'';
		var fsm = wx.getFileSystemManager();
		var base64src = function(base64data, cb) {
			var [ , format, bodyData ] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
			if (!format) {
				return new Error('ERROR_BASE64SRC_PARSE');
			}
			var filePath = `${wx.env.USER_DATA_PATH}/base64.${format}`;
			var buffer = wx.base64ToArrayBuffer(bodyData);
			fsm.writeFile({
				filePath,
				data: buffer,
				encoding: 'binary',
				success() {
					cb(filePath);
				},
				fail() {
					return new Error('ERROR_BASE64SRC_WRITE');
				}
			});
		};
		base64src(base64Url, function(filePath) {
			cos.postObject(
				{
					Bucket: configV5.Bucket,
					Region: configV5.Region,
					Key: '1.png',
					FilePath: filePath
				},
				requestCallback
			);
		});
	},

	restoreObject: function() {
		cos.restoreObject(
			{
				Bucket: configV5.Bucket,
				Region: configV5.Region,
				Key: '1.txt',
				RestoreRequest: {
					Days: 1,
					CASJobParameters: {
						Tier: 'Expedited'
					}
				}
			},
			requestCallback
		);
	},

	abortUploadTask: function() {
		cos.abortUploadTask(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				/* 必须 */ Region: configV5.Region,
				/* 必须 */
				// 格式1，删除单个上传任务
				// Level: 'task',
				// Key: '10mb.zip',
				// UploadId: '14985543913e4e2642e31db217b9a1a3d9b3cd6cf62abfda23372c8d36ffa38585492681e3',
				// 格式2，删除单个文件所有未完成上传任务
				Level: 'file',
				Key: '10mb.zip'
				// 格式3，删除 Bucket 下所有未完成上传任务
				// Level: 'bucket',
			},
			requestCallback
		);
	},

	sliceCopyFile: function() {
		// 创建测试文件
		var sourceName = '1.txt';
		var Key = '1.slicecopy.exe';
		var sourcePath = configV5.Bucket + '.cos.' + configV5.Region + '.myqcloud.com/' + sourceName;
		cos.sliceCopyFile(
			{
				Bucket: configV5.Bucket, // Bucket 格式：test-1250000000
				Region: configV5.Region,
				Key: Key,
				CopySource: sourcePath,
				SliceSize: 20 * 1024 * 1024, // 大于20M的文件用分片复制，小于则用单片复制
				onProgress: function(info) {
					var percent = parseInt(info.percent * 10000) / 100;
					var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
					console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
				}
			},
			requestCallback
		);
	},

	cancelTask: function(index) {
        return  new Promise((resolve,reject)=>{
                cosArr[index].cancelTask(TaskIdArr[index]);
                resolve({
                    type:'cancelTask',
                    status: 200
                })  
        })
    },
    
	pauseTask: function(index) {
        return  new Promise((resolve,reject)=>{
            cosArr[index].pauseTask(TaskIdArr[index]);
            resolve({
                type:'restartTask',
                status: 200
            }) 
        }) 
            // cos.pauseTask(TaskId);
	},

	restartTask: function(index) {
        return  new Promise((resolve,reject)=>{
            cosArr[index].restartTask(TaskIdArr[index]);
            resolve({
                type:'restartTask',
                status: 200
            })  
    })
		// cos.restartTask(TaskId);
	}
};

module.exports = cosFun;
